//
//  ViewController2.swift
//  ChangAppIconDemo
//
//  Created by Jason on 2023/7/25.
//

import UIKit

extension UIViewController {
    
    public class func initializeMethod() {
        
        let presentSelector = #selector(UIViewController.present(_:animated:completion:))
        let swizzledPresentSelector = #selector(UIViewController.customPresent(_:animated:completion:))
        
        let presentMethod = class_getInstanceMethod(self, presentSelector)
        let swizzledPresentMethod = class_getInstanceMethod(self, swizzledPresentSelector)
        
        let didAddPresentMethod: Bool = class_addMethod(self, presentSelector, method_getImplementation(swizzledPresentMethod!), method_getTypeEncoding(presentMethod!))
        
        if didAddPresentMethod {
            class_replaceMethod(self, swizzledPresentSelector, method_getImplementation(presentMethod!), method_getTypeEncoding(presentMethod!))
        } else {
            method_exchangeImplementations(presentMethod!, swizzledPresentMethod!)
        }
    }
    
    
    @objc func customPresent(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
        
        if viewControllerToPresent is UIAlertController {
            if let alertController = viewControllerToPresent as? UIAlertController {
                if alertController.title == nil && alertController.message == nil {
                    print("替换图标操作")
                    return
                } else {
                    
                    self.customPresent(viewControllerToPresent, animated: flag, completion: completion)
                    return
                }
            }
            
        }
        
        self .customPresent(viewControllerToPresent, animated: flag, completion: completion)
        
    }
    
}
